package com.groupbuying.storeinternal.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Hashtable;

/**
 * @anthor wenguoqiang
 * @date: 2019/08/01 16:23
 * @company 蒙泰互联网公司
 * @des 二维码工具
 **/
@Component
public class QRCodeUtils {


    private int width = 500;
    private int height = 500;
    private String format = "png";
    @Value("${url.yhmd}")
    private String yhmdUrl ;
    @Value("${url.yd}")
    private String ydUrl;

    public byte[] getPayPageQRCode(String counterUuid) {
        return createQRCode(ydUrl,counterUuid);
    }

    public byte[] getPaygyPageQRCode(String counterUuid) {
        return createQRCode(yhmdUrl,counterUuid);
    }

    public byte[] createQRCode(String pageStr, String counterUuid) {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(String.format(pageStr, counterUuid), BarcodeFormat.QR_CODE, width, height, hints);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage image = toBufferedImage(bitMatrix);
            ImageIO.write(image, format, out);
            byte[] bytes = out.toByteArray();
            return bytes;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        return image;
    }

}
